#endcoding:utf-8
class QuestionsController < ApplicationController
  layout 'user'
  before_action :logged_in? , only:[:new]
  before_action :store_location

  def index
    @kw = params[:kw].nil? ? '':params[:kw];
    @questions = Question.where("title like '%#{@kw}%'").order('created_at desc').paginate  :page=> params[:page],:per_page=> 12
  end

  def new
    @question = Question.new
  end

  def adopt
    question_id = params[:question_id]
    answer_id = params[:answer_id]
    now = Time.now.strftime("%Y-%m-%d %H:%M:%S")
    question = Question.find(question_id)
    answer = Answer.find(answer_id)
    if question.update_attributes({:fixed=>true,:fixed_at=>now})
      if answer.update_attributes({:adopted=>true,:adopted_at=>now})
        send_message(answer.user_id,message_link('您的回答被采纳了！',question_path(question)),question.id)
      end
    end
    redirect_to question
  end

  def  create
    @question = Question.new(question_params)
    if @question.save
      @link = question_url(@question)
      @user = User.find(@question.user_id)
      @followers = @user.followers
      UserMailer.account_activation(@followers,"question",@link).deliver if @followers.any?
      redirect_to @question
    else
      flash[:danger] = @question.errors.full_messages[0]
      render 'new'
    end
  end
  def show
    @question = Question.includes(:answers).find(params[:id])
    @title = @question.title
    read(@question)
  end
  private
  def question_params
    @tag = Tag.store_tag(params[:question])
    params[:question][:tag_id] = @tag.id
    params.require(:question).permit(:title,:content,:tag_id,:user_id)
  end
  def read(question)
    remoteip = request.remote_ip
    question_read_log = QuestionReadLog.where('remote_ip="'+remoteip+'" AND question_id='+question.id.to_s)
    if !question_read_log.any?
        if QuestionReadLog.new({:remote_ip=>remoteip,:question_id=>question.id}).save
          question.update_attribute(:read_num,question.read_num+1)
        end
    end
  end
end
